from bson import ObjectId
from pymongo import MongoClient
import time
import gridfs


class OBSLog:
    client = MongoClient("mongodb://root:xiong@127.0.0.1:27017/")
    db = client['obs']
    fs = gridfs.GridFS(db)
    objects = db['logs']

    def is_package_exist(self, package_id) -> bool:
        # if self.objects.count_documents({'package': package_id}):
        #     return True
        # return False
        if self.fs.exists({'package_id': package_id}):
            return True
        return False

    def create(self, package_id, log: str, project_id=None):
        # return self.objects.insert_one({'package': package_id, 'log': log})
        log_fs = self.fs.put(bytes(log, 'utf-8'))
        return self.fs.put(self.fs.get(log_fs), package_id=package_id, create_time=time.time(), project_id=project_id)

    # def update(self, package_id, log: str):
    #     return self.objects.update_one({'package': package_id, 'log': log}, {'$set': {'log': log}})

    def get_log_by_id(self, log_id):
        try:
            file = self.fs.find_one({'_id': ObjectId(log_id)})
            return file
        except gridfs.errors.NoFile:
            print('No such file')
            return None
        # return self.fs.find({'_id': log_id})

    def get_log_by_project_id(self, project_id):
        try:
            file = self.fs.find({'project_id': project_id})
            return file
        except Exception as e:
            return
            pass


    def get_all_log(self, package_id):
        return self.fs.find({'package_id': package_id})
        # return self.objects.find({'package': package_id})

    def get_latest_log(self, package_id):
        try:
            t = self.fs.find({'package_id': package_id}).sort([('uploadDate', -1)]).limit(1)[0]
            return t.read().decode('gbk')
        except Exception:
            pass
        # return self.objects.find_one({'package': package_id})

    def get_latest_log_md5(self, package_id):
        t = self.fs.find({'package_id': package_id}).sort([('uploadDate', -1)]).limit(1)[0]
        return t.md5

    def delete_all_log(self):
        for i in self.fs.find():  # or fs.list()
            self.fs.delete(i._id)


if __name__ == '__main__':
    o = OBSLog()
    # r = o.get_latest_log(4247)
    # print(r['log'])

    # for i in range(10):
    #     o.create('12138', 'test gridfs' * i)

    # print(o.is_package_exist('12138'))
    # print(o.is_package_exist('12130'))
    # r = o.get_all_log('12138')
    # for i in r:
    #     print(i.read().decode('utf-8'))
    # print()
    # print(o.get_latest_log('12138').read().decode('utf-8'))

    # o.delete_all_log()

    print(o.get_latest_log_md5(4246))
